package com.training.killerapp;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;

import com.training.killerapp.model.User;

// TODO: Create JSPs that:
//  * create a new user
//  * edit page
//  * add friends
//  * shows a user's page, along with links to friends
// TODO: Use Plexus goodness
public abstract class AbstractKillerAppServlet extends HttpServlet
{
    protected KillerApp retrieveKillerApp()
        throws ServletException
    {
        try
        {
            return ( KillerApp )getContainer().lookup( "com.training.killerapp.KillerApp" );
        }
        catch( ComponentLookupException e )
        {
            throw new ServletException( "could not lookup service com.training.killerapp.KillerApp", e );
        }
    }

    protected void releaseKillerApp( KillerApp killerApp )
        throws ServletException
    {
        try
        {
            getContainer().release( killerApp );
        }
        catch( ComponentLifecycleException e )
        {
            throw new ServletException( "Exception while releasing component", e );
        }
    }

    private PlexusContainer getContainer()
    {
        ServletContext context = getServletContext();

        return (PlexusContainer)context.getAttribute("plexus");
    }

    protected User getCurrentUser( HttpServletRequest request )
    {
        HttpSession session = request.getSession();
        return (User)session.getAttribute( "currentUser" );
    }

    protected void setCurrentUser( HttpServletRequest request, User user )
    {
        HttpSession session = request.getSession();
        session.setAttribute( "currentUser", user );
    }
}
